<template>
  <div class="m-calender-range-input" :class="{'is-focus':open}" @click="handleClick">
    <span :data-placeholder="placeholder">{{text}}</span>
    <i class="vx-arrow" style=""></i>
  </div>
</template>

<script>
import Vue from 'vue'
import 'vx-ui/lib/style/theme/tab.css'
import 'vx-ui/lib/style/theme/flexbox.css'
import 'vx-ui/lib/style/theme/arrow.css'
import 'vx-ui/lib/style/theme/calendar.css'
import 'vx-ui/lib/style/theme/calendar-range.css'
import CalendarRange from 'vx-ui/lib/calendar-range'

export default {
  components: {
    CalendarRange
  },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请选择日期区间'
    },
    disabled: {
      type: Boolean
    },
    isCustom: {
      type: Boolean,
      default: true
    },
    shortcuts: {
      type: Array,
      default () {
        return [
          {
            label: '本周',
            value () {
              let now = new Date()
              let day = now.getDay()
              let start = new Date(now.getTime() - 86400000 * (day - 1))
              let end = new Date(now.getTime() + 86400000 * (7 - day))
              return [new Date(start.getFullYear(), start.getMonth(), start.getDate()), new Date(end.getFullYear(), end.getMonth(), end.getDate())]
            }
          },
          {
            label: '本月',
            value () {
              let now = new Date()
              let year = now.getFullYear()
              let month = now.getMonth()
              return [new Date(year, month, 1), new Date(month === 11 ? year + 1 : year, month === 11 ? 0 : month + 1, 0)]
            }
          },
          {
            label: '本年',
            value () {
              let now = new Date()
              let year = now.getFullYear()
              return [new Date(year, 0, 1), new Date(year + 1, 0, 0)]
            }
          }
        ]
      }
    }
  },
  data () {
    return {
      open: false
    }
  },
  computed: {
    text () {
      if (this.value && this.value.map && this.value.length === 2) {
        let result = this.value.map(item => {
          let month = item.getMonth() + 1
          let date = item.getDate()
          return `${item.getFullYear()}-${month > 9 ? month : '0' + month}-${date > 9 ? date : '0' + date}`
        })
        return result[0] === result[1] ? result[0] : result.join('~')
      } else {
        return ''
      }
    },
    isPlaceholder () {
      return !(this.value && this.value.map && this.value.length === 2)
    }
  },
  destroyed () {
    this.$$calenderRange && this.$$calenderRange.$destroy && this.$$calenderRange.$destroy()
    this.$$calenderRange = null
  },
  methods: {
    handleClick () {
      let self = this
      if (!self.$$calenderRange && self.open === false) {
        self.open = true
        let rect = this.$el.getBoundingClientRect()
        let top = rect.top + rect.height + 'px'
        let node = document.createElement('div')
        document.body.appendChild(node)
        self.$$calenderRange = new Vue({ // eslint-disable-line
          el: node,
          data () {
            return {
              custom: false,
              value: [],
              range: ''
            }
          },
          render (h) {
            return (
              <div class="m-calender-range" style={{display: self.open ? '' : 'none', top: top}}>
                <div class="m-calender-range-opacity" onClick={this.handleBlur}></div>
                <div class="m-calender-range-inner">
                  {!this.custom && <div class="m-calender-range-button">
                    {self.shortcuts && self.shortcuts.length && <m-flexbox justify="space-between" wrap="wrap">
                      {self.shortcuts.map(item => {
                        return (
                          <mt-button
                            type={this.isActive(item.value()) ? 'primary' : undefined}
                            onClick={this.handleShortcuts.bind(this, item.value())}>
                            {item.label}
                          </mt-button>
                        )
                      })}
                    </m-flexbox>}
                    {self.isCustom && <mt-button size="large" onClick={this.handleCustom} style="margin-top:10px">自定义时间范围</mt-button>}
                  </div>}
                  {<div style={{display: this.custom ? '' : 'none'}}>
                    <CalendarRange value={this.value} onChange={this.handleChange}/>
                    <m-divider/>
                    <m-flexbox justify="space-between">
                      <mt-button type="origin" onClick={this.handleCancel}>取消</mt-button>
                      <mt-button type="origin" onClick={this.handleClear}>清空</mt-button>
                      <mt-button type="link" onClick={this.handleSumbit}>确定</mt-button>
                    </m-flexbox>
                  </div>}
                </div>
              </div>
            )
          },
          destroyed () {
            this.$el && this.$el.parentNode && this.$el.parentNode.removeChild(this.$el)
          },
          methods: {
            isActive (value) {
              if (self.value && self.value.length === 2 && value && value.length === 2) {
                if (self.value[0].getTime() === value[0].getTime() && self.value[1].getTime() === value[1].getTime()) {
                  return true
                }
              }
              return false
            },
            handleBlur () {
              self.open = false
            },
            handleCustom () {
              this.custom = !this.custom
              this.range = ''
            },
            handleCancel () {
              this.handleCustom()
              self.open = false
            },
            handleChange (value) {
              this.value = value
            },
            handleClear () {
              this.value = []
            },
            handleSumbit () {
              self.$emit('input', this.value).$emit('change', this.value)
              self.open = false
              this.handleCustom()
            },
            handleShortcuts (value) {
              self.open = false
              self.$emit('input', value).$emit('change', value)
            }
          }
        })
      } else {
        self.open = !self.open
        if (self.$$calenderRange) {
          self.$$calenderRange.custom = false
        }
      }
    }
  }
}
</script>

<style lang="scss">
  .m-calender-range{
    position:fixed;
    top:0;
    left:0;
    width:100%;
    z-index:100;
    height:100%;
    &-opacity{
      position:absolute;
      top:0;
      left:0;
      width:100%;
      height:100%;
      background:$color-overlay;
    }
    &-input{
      border:0;
      border-box:border-box;
      display:inline-block;
      line-height:0.8rem;
      .vx-arrow{
        height: 8px;
        width: 8px;
        border-color: transparent rgb(153, 153, 153) rgb(153, 153, 153) transparent;
        position:relative;
        top:-4px;
      }
      &.is-focus{
        .vx-arrow{
          transform: rotate(225deg);
          top:2px;
        }
      }
      span{
        @include placeholder;
      }
    }
    &-inner{
      background:#fff;
      position:relative;
      z-index:1;
    }
    &-button{
      padding:10px;
      button{
        margin:5px 0;
      }
    }
    .vx-tab-underline{
      border-color:$color-primary;
      transform: scaleX(0.2)
    }
    .vx-tab-item-active{
      color:$color-primary;
    }
    .vx-calendar-date{
      height:0.9rem;
      line-height:0.9rem;
      &.is-end,&.is-start{
        background:$color-primary;
        position:relative;
        span{
          margin-top:0.12rem;
          display:block;
          line-height: 0.35rem;
          &:after{
            content:'开始';
            font-size:0.24rem;
            display:block;
          }
        }
      }
      &.is-end{
        span:after{
          content:'结束';
        }
      }
      &.is-active{
        background:rgba($color-primary, 0.15);
      }
      &.is-today{
        color:$color-primary;
      }
    }
    .vx-calendar-range-month,.vx-calendar-range-quarter{
      height:0.9rem;
      line-height:0.9rem;
      &.is-active{
        background:$color-primary;
      }
    }
  }
</style>
